const express = require(`express`)
const passport = require('passport');
const asyncHandler = require('express-async-handler');
const deviceCtrl = require('../controllers/device.controller');

const router = express.Router()

router.use(passport.authenticate('jwt', { session: false }))

router.route('/').get(asyncHandler(getAll));
router.route('/').post(asyncHandler(add));
router.route('/').put(asyncHandler(edit));
router.route('/:id').get(asyncHandler(getOne));
router.route('/:id').delete(asyncHandler(remove));

// const path = require('path'); //系统路径模块
// const fs = require('fs'); //文件模块
// const device_json = path.join(path.resolve('./'), 'data/device.json'); 

async function getAll(req, res){
    const user = req.user
    const device = await deviceCtrl.findAll(user)
    res.jsonp({ code: 20000, data: device })
}

async function getOne(req, res){
    let data = await deviceCtrl.findOne(req.params.id);
    console.log(data)
    res.json({ code: 20000, data: data })
}

async function add(req, res){
    let device = await deviceCtrl.insert(req.body);
    res.json({ code: 20000, message: '添加成功' })
}

async function remove(req, res){
    let err = await deviceCtrl.remove(req.params.id);
    if (!err) {
        res.json({ code: -1, message: '删除设备失败' })
    }
    res.json({ code: 20000, message: '删除设备成功' })
}

async function edit(req, res){
    let err = await deviceCtrl.edit(req.body)
    if (!err) {
        res.json({ code: -1, message: '修改设备失败' })
    }
    res.json({ code: 20000, message: '修改设备成功' })
}


module.exports = router